package com.hmh.student.system.controller;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmh.student.system.entity.SysRole;
import com.hmh.student.system.entity.SysUser;
import com.hmh.student.system.entity.SysUserRole;
import com.hmh.student.system.result.Result;
import com.hmh.student.system.service.ISysRoleService;
import com.hmh.student.system.service.ISysUserRoleService;
import com.hmh.student.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xyf
 * @since 2025-04-15
 */
@RestController
@RequestMapping("/sysUser")
public class SysUserController {

    @Autowired
    ISysUserService sysUserService;
    @Autowired
    ISysRoleService sysRoleService;
    @Autowired
    ISysUserRoleService sysUserRoleService;

    @PostMapping("/save")
    public Map<String,Object> save(@RequestBody SysUser sysUser) {

        Map<String,Object> map = new HashMap<String,Object>();
        sysUserService.save(sysUser);
        map.put("success","success");
        return map;
    }

    @PostMapping("/addUser")
    public Map<String, Object> addUser(@RequestBody SysUser sysUser) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = sysUserService.addUser(sysUser);
            result.put("success", success);
            result.put("userId", sysUser.getUserId()); // 返回生成的 userId
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @GetMapping("/login")
    public Map<String, Object> login(@ModelAttribute SysUser sysUser) {
        Map<String, Object> response = new HashMap<>();

        SysUser dbUser = sysUserService.login(sysUser.getUserName(),sysUser.getPassword());

        if (dbUser != null) {
            response.put("success", true);
            response.put("message", "登录成功");
        } else {
            response.put("success", false);
            response.put("message", "用户名或密码错误");
        }

        return response;
    }

    @PutMapping("/updateUser")
    public Map<String, Object> updateUser(@RequestBody SysUser user) {
        Map<String, Object> map = new HashMap<>();
        try {
            sysUserService.updateById(user);
            map.put("msg", "success");
        } catch (Exception e) {
            map.put("msg", "更新失败: " + e.getMessage());
        }
        return map;
    }

    @DeleteMapping("/deleteUser")
    public Map<String, Object> deleteUser(@RequestParam Integer userId) {
        Map<String, Object> map = new HashMap<>();
        try {
            sysUserService.removeById(userId);
            map.put("msg", "success");
        } catch (Exception e) {
            map.put("msg", "删除失败");
        }
        return map;
    }

    @GetMapping("/pageUser")
    public Page<SysUser> pageUser(
            @RequestParam(required = false) String userName,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "1") Integer current) {
        return sysUserService.pageUser(userName, pageSize, current);
    }

    // 获取所有角色列表
    @GetMapping("/getAllRole")
    public Result getAllRole() {
        List<SysRole> roles = sysRoleService.list();
        return Result.success(roles);
    }

    // 获取用户当前角色
    @GetMapping("/getRoleByUserId")
    public Result getRoleByUserId(@RequestParam Integer userId) {
        if (userId == null) {
            return Result.fail("用户ID不能为空");
        }
        Integer roleId = sysUserRoleService.getRoleByUserId(userId);
        return roleId != null
                ? Result.success(roleId)
                : Result.success("用户未分配角色", null);
    }

    // 分配角色
    @PostMapping("/assignRole")
    public Result assignRole(
            @RequestParam Integer userId,
            @RequestParam Integer roleId
    ) {
        if (userId == null || roleId == null) {
            return Result.fail("用户ID和角色ID不能为空");
        }
        try {
            sysUserRoleService.assignRoleToUser(userId, roleId);
            return Result.success("角色分配成功");
        } catch (IllegalArgumentException e) {
            return Result.fail(e.getMessage());
        } catch (Exception e) {
            return Result.fail("分配角色失败: " + e.getMessage());
        }
    }


}

